package tylerp.dnd;

import java.util.Scanner;

public class Parser {

    /**
     * This method takes a user created String and makes a roll based on
     * that String.
     * @param parseString the String containing the roll information
     * @return the formatted String representing this roll
     */
    public static String parse(String parseString) {
        // Format the input String
        parseString = parseString.replaceAll("\\s", "");
        parseString = parseString.toLowerCase();

        if (!parseString.contains("d") || parseString.length() < 2) {
            throw new java.util.InputMismatchException();
        }

        // Make the Scanner and set it to look for the first number
        Scanner sc = new Scanner(parseString);
        sc.useDelimiter("d");

        // Get the number of dice
        int numDice = 1;
        if (parseString.charAt(0) != 'd') {
            numDice = sc.nextInt();
        }

        // Remake the Scanner and set it to look for the remaining numbers
        try {
            sc = new Scanner(sc.next());
        } catch (java.util.NoSuchElementException e) {
            sc = new Scanner(parseString.substring(1));
        }
        boolean plus = true;
        sc.useDelimiter("\\+");
        if (!sc.hasNextInt()) {
            sc.useDelimiter("-");
            plus = false;
        }

        // Get the number of sides on each dice
        int numSides = sc.nextInt();

        // Look for the modifier if it exists
        int modif = 0;
        if (sc.hasNextInt()) {
            modif = sc.nextInt();
            if (!plus) {
                modif *= -1;
            }
        }

        return Roller.roll(numDice, numSides, modif);
    }
}

